﻿
using Arction.Wpf.BindableCharting;
using Arction.Wpf.BindableCharting.Axes;
using Arction.Wpf.BindableCharting.SeriesXY;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPF_Lightningchart_UI_Demo
{
    public partial class BodePlotControl : UserControl
    {
        private LightningChartUltimate BTopChart;
        private AxisX BTopChartAxisX;
        private AxisY BTopChartAxisY;

        public BodePlotControl()
        {
            InitializeComponent();
            Loaded += (r, s) => LCPageBTopChartLoad();
            Unloaded += (r, s) => BTopChart?.Dispose();
        }

        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<SensorData>), typeof(BodePlotControl),
                new PropertyMetadata(null, OnItemsSourceChanged));

        public ObservableCollection<SensorData> ItemsSource
        {
            get => (ObservableCollection<SensorData>)GetValue(ItemsSourceProperty);
            set => SetValue(ItemsSourceProperty, value);
        }

        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (BodePlotControl)d;
            if (e.OldValue is ObservableCollection<SensorData> oldData)
                oldData.CollectionChanged -= control.OnCollectionChanged;

            if (e.NewValue is ObservableCollection<SensorData> newData)
            {
                newData.CollectionChanged += control.OnCollectionChanged;
                control.UpdateChart(newData);
            }
        }

        private void OnCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (BTopChart == null) return;

            BTopChart.BeginUpdate();
            switch (e.Action)
            {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    foreach (SensorData newData in e.NewItems)
                        AddNewPointToChart(newData);
                    BTopChart.ViewXY.ZoomToFit();
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    foreach (SensorData removedData in e.OldItems)
                        RemovePointFromChart(removedData);
                    BTopChart.ViewXY.ZoomToFit();
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
                    ClearChart();
                    UpdateChart(ItemsSource);
                    break;
            }
            BTopChart.EndUpdate();
        }

        private void UpdateChart(ObservableCollection<SensorData> newData)
        {
            if (newData == null || BTopChart == null) return;

            BTopChart.BeginUpdate();
            var series = GetOrCreateSeries();
            foreach (var data in newData)
                AddNewPointToChart(data, series);
            BTopChart.ViewXY.ZoomToFit();
            BTopChart.EndUpdate();
        }

        private void AddNewPointToChart(SensorData data, PointLineSeries series = null)
        {
            if (series == null) { series = GetOrCreateSeries(); }
        }

        private void RemovePointFromChart(SensorData data)
        {
            if (BTopChart.ViewXY.PointLineSeries.Count == 0) return;

            var series = BTopChart.ViewXY.PointLineSeries[0];

            // 获取匹配的点
            var pointToRemove = series.Points.FirstOrDefault(p => p.X == data.Frequency && p.Y == data.Magnitude);

            // 检查是否找到匹配的点
            if (!pointToRemove.Equals(default(SeriesPoint)))
            {
                series.DeletePointsBeforeX(pointToRemove.X);
            }
        }


        private PointLineSeries GetOrCreateSeries()
        {
            if (BTopChart.ViewXY.PointLineSeries.Count > 0)
                return BTopChart.ViewXY.PointLineSeries[0];

            var series = new PointLineSeries
            {
                Title = { Text = "Bode Plot Data", Color = Colors.Yellow },
                PointsVisible = true,
                PointStyle = { Color1 = Colors.White, Color2 = Colors.SkyBlue, Height = 5f, Width = 5f },
                LineStyle = { Width = 2f, Color = Colors.Pink },
                MouseInteraction = false
            };
            BTopChart.ViewXY.PointLineSeries.Add(series);
            return series;
        }

        private void ClearChart()
        {
            if (BTopChart?.ViewXY.PointLineSeries.Count > 0)
                BTopChart.ViewXY.PointLineSeries[0].Clear();
        }

        private void LCPageBTopChartLoad()
        {
            BTopChart = new LightningChartUltimate();
            BTopChart.BeginUpdate();
            ConfigureChartBase();
            BTopChartAxisX = BTopChart.ViewXY.XAxes[0];
            BTopChartAxisY = BTopChart.ViewXY.YAxes[0];
            ConfigureAxis(BTopChartAxisX, BTopChartAxisY, 0, 50, 0, 100);
            BTopChart.EndUpdate();
            TopChart.Children.Add(BTopChart);
        }

        private void ConfigureChartBase()
        {
            BTopChart.ColorTheme = ColorTheme.LightGray;
            BTopChart.Title.Text = "";
            BTopChart.Title.Color = Colors.DeepSkyBlue;
            BTopChart.Padding = new Thickness(0);
            BTopChart.Margin = new Thickness(0);
            BTopChart.ChartBackground.Color = Colors.Transparent;

            var legendBox = BTopChart.ViewXY.LegendBoxes[0];
            legendBox.Layout = LegendBoxLayout.Vertical;
            legendBox.Position = LegendBoxPositionXY.SegmentTopLeft;
            legendBox.MoveByMouse = false;
            legendBox.AllowMouseResize = false;
            legendBox.Shadow.Visible = false;
            legendBox.BorderWidth = 0;
            legendBox.Visible = false;
        }

        private void ConfigureAxis(AxisX axisX, AxisY axisY, double x1, double x2, double y1, double y2)
        {
            axisX.ScrollMode = XAxisScrollMode.None;
            axisX.ValueType = AxisValueType.Number;
            axisX.AxisColor = Colors.Black;
            axisX.Title.Text = "";
            axisX.SetRange(x1, x2);

            axisY.AxisColor = Colors.Black;
            axisY.Title.Fill.GradientColor = Colors.Black;
            axisY.SetRange(y1, y2);
            axisY.Title.Text = "";
        }



        private void OpenSettings_Click(object sender, RoutedEventArgs e)
        {
            SettingsWindow settingsWindow = new SettingsWindow();
            if (settingsWindow.ShowDialog() == true)
            {
                // 使用返回的设置值
                string property1 = settingsWindow.Property1;
                string property2 = settingsWindow.Property2;

                // 根据需要更新控件的属性
            }
        }


    }
}
